package com.tonyodev.fetch2core;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import org.jetbrains.annotations.NotNull;

/**
 * 日志输出
 *
 * @since 2021-05-20
 */
public class FetchLogger implements Logger {
    private boolean enabled;
    private String tag;

    /**
     * 构造函数
     *
     * @param enabled 日志开关
     * @param tag 日志标签
     */
    public FetchLogger(boolean enabled, @NotNull String tag) {
        this.enabled = enabled;
        this.tag = tag;
    }

    /**
     * 构造函数
     */
    public FetchLogger() {
        this(FetchCoreDefaults.DEFAULT_LOGGING_ENABLED, FetchCoreDefaults.DEFAULT_TAG);
    }

    @NotNull
    public String getTag() {
        return this.tag;
    }

    public void setTag(@NotNull String tag) {
        this.tag = tag;
    }

    private String getLoggingTag() {
        return this.tag.length() > 23 ? FetchCoreDefaults.DEFAULT_TAG : this.tag;
    }

    @Override
    public boolean getEnabled() {
        return this.enabled;
    }

    @Override
    public void setEnabled(boolean var1) {
        this.enabled = var1;
    }

    @Override
    public void d(String message) {
        if (enabled) {
            HiLog.debug(new HiLogLabel(HiLog.LOG_APP, 0, getLoggingTag()), "%{public}s", message);
        }
    }

    @Override
    public void d(String message, Throwable throwable) {
        if (enabled) {
            HiLog.debug(new HiLogLabel(HiLog.LOG_APP, 0, getLoggingTag()), "%{public}s %{public}s", message, HiLog.getStackTrace(throwable));
        }
    }

    @Override
    public void e(String message) {
        if (enabled) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, getLoggingTag()), "%{public}s", message);
        }
    }

    @Override
    public void e(String message, Throwable throwable) {
        if (enabled) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, getLoggingTag()), "%{public}s %{public}s", message, HiLog.getStackTrace(throwable));
        }
    }
}
